/**
 * Created by charsen on 16/5/26.
 */
directives.directive('fieldItem', ["$rootScope", "tools", "$timeout", function ($rootScope, tools, $timeout) {
    return {
        restrict: 'AE',
        scope: {
            menu: '=json'
        },
        replace: true,
        link: function (scope, element, attr) {
            var index = $(element).closest('.ui.dropdown').index();
            var type = attr.fieldType;
            scope.meaTypeNames = {
                sum: '总和',
                avg: '平均',
                count: '计数',
                max: '最大值',
                min: '最小值'
            };

            scope.select = function (e) {
                $(element).css('zIndex', ++dropdown_z_index);
            }

            // 存放在拖拽的过程中需要传输的数据
            $(element)[0].addEventListener('dragstart', function (ev) {
                ev.dataTransfer.setData("Text", JSON.stringify({
                    type: type,
                    index: index
                }));
            });

            var clientX = -1;
            var dir = "";

            $(element)[0].addEventListener('dragover', function (ev) {
                if (ev.clientX > clientX) {
                    $rootScope.setDraggedField(type, index, dir = 'right');
                } else if (ev.clientX < clientX) {
                    $rootScope.setDraggedField(type, index, dir = 'left');
                } else {
                    $rootScope.setDraggedField(type, index, dir);
                }
                clientX = ev.clientX;
                ev.preventDefault();
            });

            $timeout(function () {
                $(element).dropdown({
                    action: 'nothing'
                });
            }, 50);

            $rootScope.$on('FIELD_ITEM_DROP_OFF', function () {
                $(element).dropdown('hide');
            });
        },
        templateUrl: "/trend-new-BI/app/components/common/chartManager/fieldItem/fieldItemView.html"
    }
}]);